package cn.fl.arbitration.utils;

import cmm.mid.core.framework.page.DataResultVO;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.utils.BaseLogUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Iterator;
import java.util.Set;

/**
 * @Auther: admin
 * @Date: 2018/11/26 16:52
 * @Description:
 */
public class ValidateUtils {
    private static final Logger logger = LoggerFactory.getLogger(ValidateUtils.class);
    private ValidateUtils(){};

    private static Validator getValidator() {
        ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
        Validator validator = validatorFactory.getValidator();
        return validator;
    }

    public static  <T> DataResultVO validate(T t){
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "新增成功!");
        //验证参数
        if(t==null){
            result.setInfo("参数不能为空");
            result.setSuccess(0);
            return result;
        }
        BaseLogUtils.info(logger,"validate","请求对象为:"+t.toString());
        Set<ConstraintViolation<T>> validate = getValidator().validate(t);
        Iterator<ConstraintViolation<T>> iterator = validate.iterator();
        StringBuilder stringBuilder = new StringBuilder();
        while (iterator.hasNext()){
            ConstraintViolation<T> next = iterator.next();
            stringBuilder.append("校验：").append(next.getPropertyPath()).append(next.getMessage()).append(" ");
        }
        if(stringBuilder.toString().length()>0){
            result.setInfo(stringBuilder.toString());
            result.setSuccess(0);
            return result;
        }
        return result;
    }

}
